package cn.cuiliangpeng.user.controller;

import cn.cuiliangpeng.basic.domain.dto.RegisterDto;
import cn.cuiliangpeng.user.service.IUserService;
import cn.cuiliangpeng.user.domain.User;
import cn.cuiliangpeng.user.query.UserQuery;
import cn.cuiliangpeng.basic.utils.AjaxResult;
import cn.cuiliangpeng.basic.utils.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
* 后端接口类；
*/
@RestController
@RequestMapping("/user" )
public class UserController {

    @Autowired
    public IUserService userService;

    /**
     * 接口：添加或修改
     * @param user 传递的实体
     * @return AjaxResult 响应给前端
     */
    @PutMapping
    public AjaxResult updateAndAdd(@RequestBody User user) {
        if ( user.getId() != null){
                userService.update(user);
        } else{
                userService.save(user);
        }
        return AjaxResult.me();
    }

    /**
    * 接口：删除
    * @param id
    * @return AjaxResult 响应给前端
    */
    @DeleteMapping(value = "/{id}" )
    public AjaxResult delete(@PathVariable("id" ) Long id) {
            userService.delete(id);
        return AjaxResult.me();
    }

    /**
    * 接口：批量删除
    * @param ids
    * @return AjaxResult 响应给前端
    */
    @PatchMapping
    public AjaxResult patch(@RequestBody Long[] ids) {
            userService.patch(ids);
        return AjaxResult.me();
    }
    /**
    * 接口：查询单个对象
    * @param id
    */
    @GetMapping("/{id}" )
    public User findById(@PathVariable("id" ) Long id) {
        return userService.findById(id);
    }

    /**
    * 接口：查询所有
    * @return
    */
    @GetMapping
    public List<User> findAll() {
        return userService.findAll();
    }


    /**
     * 接口：分页查询或高级查询
     * @param query 查询对象
     * @return PageList 分页对象
     */
    @PostMapping
    public PageList<User> queryPage(@RequestBody UserQuery query) {
        return userService.queryPage(query);
    }

    /**
     * 手机号码注册
     * @param dto
     * @return
     */
    @PostMapping("/register/phone")
    public AjaxResult phoneRegister(@RequestBody @Valid RegisterDto dto){
        return userService.phoneRegister(dto);
    }

}
